#include "loaderply.h"
#include <cstdio>
#include <cstring>

bool LoaderPLY::Load(const char *filename) {
  FILE *fp = fopen(filename, "r");
  if (!fp) return false;

  char command[256];
  int vertex_count = -1, face_count = -1;

  while (true) {
    fscanf(fp, "%s", &command[0]);

    if (feof(fp) || strcmp(command, "end_header") == 0) {
      break;
    }
    else if (strcmp(command, "element") == 0) {
      fscanf(fp, "%s", &command[0]);
      if (strcmp(command, "vertex") == 0) {
        fscanf(fp, "%d", &vertex_count);
      }
      else if (strcmp(command, "face") == 0) {
        fscanf(fp, "%d", &face_count);
      }
    }

    fgets(&command[0], sizeof(command), fp);
  }

  if (vertex_count < 0 || face_count < 0) {
    fclose(fp);
    return false;
  }

  vertex_data_.resize(vertex_count * 2);
  for (int i = 0; i < vertex_count; ++i) {
    glm::vec3 v;
    fscanf(fp, "%f %f %f", &v.x, &v.z, &v.y);
    v.z = -v.z;
    vertex_data_[i * 2] = v;

    fscanf(fp, "%f %f %f", &v.x, &v.z, &v.y);
    v.z = -v.z;
    vertex_data_[i * 2 + 1] = v;
  }

  int c;
  index_data_.resize(face_count * 3);

  for (int i = 0; i < face_count; ++i) {
    const int idx = i * 3;
    fscanf(fp, "%d %d %d %d", &c, &index_data_[idx], &index_data_[idx+1],
           &index_data_[idx+2]);
  }

  return true;
}
